<template>
    <div class="page_root" :key="queryUpdateFlag" data-page-name="参数设置" data-page-identification="k_disan4rqui">
        <a-spin :spinning="pageLoading.loading" :tip="pageLoading.tip">
            <!-- begin vid_y4ba5rydby 自定义模板_2z8n7geoj6 -->
            <!--          新建/编辑参数-->
            <a-modal
                :visible="state.modalVisible"
                :title="state.modalTitle"
                centered
                width="1200"
                :mask-closable="false"
                :keyboard="false"
                @ok="submitModal"
                @cancel="cancelModal"
                destroy-on-close
                :ok-button-props="{ loading: state.okLoading }"
            >
                <div class="form-div">
                    <a-form :model="state.modalForm" ref="modalRef">
                        <a-row>
                            <a-col :span="24">
                                <a-form-item
                                    label="参数键名"
                                    name="parameterKey"
                                    :rules="[{ required: true, message: '请输入', trigger: 'blur' }]"
                                >
                                    <a-input
                                        :placeholder="inputHolder"
                                        v-model:value="state.modalForm.parameterKey"
                                        maxlength="60"
                                        show-count
                                    />
                                </a-form-item>
                            </a-col>
                            <a-col :span="24">
                                <a-form-item
                                    label="参数键值"
                                    name="parameterValue"
                                    :rules="[{ required: false, message: '请输入', trigger: 'blur' }]"
                                >
                                    <a-textarea
                                        :placeholder="inputHolder"
                                        v-model:value="state.modalForm.parameterValue"
                                        maxlength="1000"
                                        show-count
                                        :rows="4"
                                    />
                                </a-form-item>
                            </a-col>
                            <a-col :span="24">
                                <a-form-item
                                    label="是否启用"
                                    name="disabled"
                                    :rules="[{ required: true, message: '请输入', trigger: 'blur' }]"
                                >
                                    <a-select
                                        :options="[
                                            {
                                                label: '启用',
                                                value: false
                                            },
                                            {
                                                label: '停用',
                                                value: true
                                            }
                                        ]"
                                        :placeholder="selectHolder"
                                        v-model:value="state.modalForm.disabled"
                                    />
                                </a-form-item>
                            </a-col>
                            <a-col :span="24">
                                <a-form-item
                                    label="备注"
                                    name="description"
                                    :rules="[{ required: false, message: '请输入', trigger: 'blur' }]"
                                >
                                    <a-textarea
                                        :maxlength="300"
                                        show-count
                                        :placeholder="inputHolder"
                                        v-model:value="state.modalForm.description"
                                        :rows="4"
                                    />
                                </a-form-item>
                            </a-col>
                        </a-row>
                    </a-form>
                </div>
            </a-modal>
            <!--          新建/编辑参数-->
            <div class="body">
                <div class="top-search">
                    <a-row :gutter="24">
                        <a-col :span="6">
                            <a-form-item label="参数键名" :label-col="{ span: 4 }" :wrapper-col="{ span: 20 }">
                                <a-input
                                    :placeholder="inputHolder"
                                    v-model:value="state.filter.parameterKey"
                                />
                            </a-form-item>
                        </a-col>
                        <a-col :span="6">
                            <a-form-item label="是否启用">
                                <a-select
                                    :options="[
                                        {
                                            label: '启用',
                                            value: false
                                        },
                                        {
                                            label: '停用',
                                            value: true
                                        }
                                    ]"
                                    :placeholder="selectHolder"
                                    v-model:value="state.filter.disabled"
                                />
                            </a-form-item>
                        </a-col>
                        <a-col :span="6">
                            <a-space>
                                <a-button type="primary" @click="getData(true)">查询</a-button>
                                <a-button type="primary" @click="resetData" ghost>重置</a-button>
                            </a-space>
                        </a-col>
                    </a-row>
                </div>
                <div class="content">
                    <div class="table-top">
                        <div class="tip-msg">参数列表</div>

                        <div class="right-btn">
                            <a-button type="primary" @click="handleAdd">新建</a-button>
                        </div>
                    </div>
                    <div class="table-box">
                        <a-table
                            :columns="columns"
                            :data-source="state.dataSource"
                            bordered
                            :pagination="pagination"
                            :loading="state.tableLoading"
                            @change="handleTableChange"
                        >
                            <template #bodyCell="{ record, text, column, index }">
                                <template v-if="column.dataIndex === 'disabled'">
                                    {{ text == false ? '启用' : '停用' }}
                                </template>
                                <template v-if="column.dataIndex === 'opration'">
                                    <a-space :size="0">
                                        <a-button size="small" type="link" @click="handleEdit(record)">编辑</a-button>
                                        <a-popconfirm
                                            title="确定删除?"
                                            ok-text="确定"
                                            cancel-text="取消"
                                            @confirm="handleDelete(record.id)"
                                            @cancel="cancel"
                                        >
                                            <a-button size="small" type="link">删除</a-button>
                                        </a-popconfirm>
                                    </a-space>
                                </template>
                            </template>
                        </a-table>
                    </div>
                </div>
            </div>
            <!-- end vid_y4ba5rydby 自定义模板_2z8n7geoj6 -->
        </a-spin>
    </div>
</template>
<script setup lang="tsx">
    import {
        h,
        ref,
        reactive,
        toRaw,
        markRaw,
        watch,
        computed,
        onBeforeMount,
        onMounted,
        onBeforeUnmount,
        onUnmounted,
        onActivated,
        onDeactivated
    } from 'vue'
    import { useRoute, useRouter } from 'vue-router'
    const router = useRouter()
    const route = useRoute()
    import { get, post, put, del, request, requestWithHeaders } from '@/utils/http/Axios'
    import {
        cloneDeep,
        localGet,
        merge,
        getDifferenceArray,
        traversalTreeStructure,
        checkCaseCondition,
        renderStringInTemplate,
        handleBreadcrumbJump,
        throttle,
        permission,
        getComponentParamsValue
    } from '@/utils/index'
    import { isNullOrEmpty, isEmptyArr, isNullOrUnDef, isContained, isArray, isEmpty, isObject } from '@/utils/is'
    import dayjs from 'dayjs'
    import { getPagePcChartsDataSourceConvert } from '@/utils/chart'
    import { message, notification, Modal } from 'ant-design-vue'
    import {
        propertyFormatByNumber,
        propertyFormatByPercentage,
        propertyFormatByDate,
        parseSubFromDataList
    } from '@/utils/format'
    import colorTheme from '@/design/custom-theme.json'
    /*** PUBLISH_EXEGESIS ***
 import UserTableRecords from '@/model/UserTableRecords';
 import { getAppBaseUrl } from '@/utils/index';
 import { sendToken } from "@/hooks/useIframeToken";
 import { useSystemStore } from "@/store/modules/system";
 const systemStore = useSystemStore();
 *** PUBLISH_EXEGESIS ***/

    // 获取传入的流程ID和组件参数
    const props = defineProps({
        'processInstanceId': {
            type: [String, Number, Boolean],
            default: undefined
        }
    })
    const immediateWatch = (source, callback) => {
        watch(source, callback, { deep: true, immediate: true })
    }

    /* -------------------------- 属性定义 -------------------------- */

    const setTimeOutList = []
    const pageLoading = reactive({
        loading: false,
        tip: undefined
    })
    const authInfo = localGet('app-user-store')

    // 处理校验
    const setSubFormName = (parentInfo, name) => {
        return [parentInfo.parents, parentInfo.cycleIndex, name]
    }

    /* ========================== 属性定义 ========================== */

    /* -------------------------- 元素数据引用 -------------------------- */

    /* ========================== 元素数据引用 ========================== */

    /* -------------------------- 页面数据 -------------------------- */

    /* ========================== 页面数据 ========================== */

    /* -------------------------- 响应 -------------------------- */

    /* ========================== 响应 ========================== */

    /* -------------------------- 函数 -------------------------- */

    /* ========================== 函数 ========================== */

    /* -------------------------- 页面参数 -------------------------- */

    const pageParameter_state = reactive({
        'processInstanceId': props.processInstanceId ?? route.query.processInstanceId
    })

    /* ========================== 页面参数 ========================== */

    /* -------------------------- 组件事件处理方法 -------------------------- */

    // ---------------------------- 组件数据同步 ----------------------------

    // ============================ 组件数据同步 ============================

    /* ========================== 组件事件处理方法 ========================== */

    /* -------------------------- 生命周期 -------------------------- */
    // 用于参数变更后重新执行自定义指令
    const queryUpdateFlag = ref(0)
    onMounted(() => {})

    onUnmounted(() => {
        // 销毁定时器
        setTimeOutList.forEach(({ repeat, timer }) => {
            repeat ? clearInterval(timer) : clearTimeout(timer)
        })
    })

    /* ========================== 生命周期 ========================== */

    /* -------------------------- 数据关联处理 -------------------------- */

    /* -------------------------- 表单数据同步 -------------------------- */
    /* ========================== 表单数据同步 ========================== */

    /* ========================== 数据关联处理 ========================== */

    /* -------------------------- 不同组件自定义的处理逻辑 -------------------------- */

    /* ========================== 不同组件自定义的处理逻辑 ========================== */

    // ================================定制化逻辑========================================
    onMounted(() => {
        getData()
        calcTableHeight()
        window.addEventListener('resize', calcTableHeight)
    })
    const headerOffset = ref(210)
    const calcTableHeight = () => {
        state.tableHeight = window.innerHeight - 180 - headerOffset.value
    }
    onBeforeUnmount(() => {
        window.removeEventListener('resize', calcTableHeight)
    })
    const inputHolder = '请输入'
    const selectHolder = '请选择'
    const state = reactive({
        filter: {
            parameterKey: undefined,
            description: undefined,
            disabled: undefined
        },
        tableHeight: 600,
        modalForm: {
            parameterKey: undefined,
            description: undefined,
            disabled: undefined
        },
        dataSource: [],
        tableLoading: false,
        okLoading: false,
        modalVisible: false,
        modalTitle: ''
    })
    const pagination = ref({
        current: 1,
        pageSize: 10,
        showSizeChanger: true,
        total: 0,
        pageSizeOptions: ['10', '20', '40', '60', '80', '100'],
        showTotal: total =>
            `共 ${total} 个项目 第 ${pagination.value.current}/${Math.ceil(total / pagination.value.pageSize)}页`
    })
    const columns = ref([
        {
            title: '参数键名',
            dataIndex: 'parameterKey',
            resizable: true,
            align: 'center',
            ellipsis: true
        },
        {
            title: '参数键值',
            dataIndex: 'parameterValue',
            resizable: true,
            align: 'center',
            ellipsis: true
        },
        {
            title: '是否启用',
            dataIndex: 'disabled',
            resizable: true,
            align: 'center',
            width: 100,
            ellipsis: true
        },
        {
            title: '备注',
            dataIndex: 'description',
            resizable: true,
            align: 'center',
            ellipsis: true
        },
        {
            title: '操作',
            dataIndex: 'opration',
            align: 'center',
            width: 120
        }
    ])
    function getData(flag) {
        if (flag) {
            pagination.value.current = 1
        }
        state.tableLoading = true
        post('/solution-ppm-basic-data/api/v1/parameterInfo/list/search', {
            ...state.filter,
            pageNumber: pagination.value.current,
            pageSize: pagination.value.pageSize
        })
            .then(data => {
                if (data.code !== 200) {
                    message.error(data.message)
                    return
                }
                state.dataSource = data.data.content
                pagination.value.total = data.data.totalElements
            })
            .finally(() => {
                state.tableLoading = false
            })
    }
    function resetData() {
        state.filter = { parameterKey: undefined, description: undefined, disabled: undefined }
        getData(true)
    }

    const handleTableChange = (paginationInfo, filters, sorter) => {
        pagination.value.current = paginationInfo.current
        pagination.value.pageSize = paginationInfo.pageSize
        getData()
    }
    const modalRef = ref(null)
    function handleAdd() {
        state.modalVisible = true
        state.modalTitle = '新建参数'
    }
    const currentData = ref({})
    function handleEdit(record) {
        console.log(record)
        currentData.value = record
        let data = cloneDeep(record)
        Object.assign(state.modalForm, data)
        state.modalVisible = true
        state.modalTitle = '编辑参数'
    }
    function handleDelete(id) {
        del(`/solution-ppm-basic-data/api/v1/parameterInfo/${id}`).then(data => {
            if (data.code !== 200) {
                message.error(data.message)
                return
            }
            message.success(data.message)
            getData()
        })
    }
    function submitModal() {
        modalRef.value.validate().then(() => {
            const api = currentData.value.id ? put : post
            state.okLoading = true
            api('/solution-ppm-basic-data/api/v1/parameterInfo', state.modalForm)
                .then(data => {
                    if (data.code !== 200) {
                        message.error(data.message)
                        return
                    }
                    message.success(data.message)
                    cancelModal()
                    getData()
                })
                .finally(() => {
                    state.okLoading = false
                })
        })
    }
    function cancelModal() {
        state.modalVisible = false
        state.modalForm = {
            parameterKey: undefined,
            description: undefined,
            disabled: undefined
        }
        currentData.value = {}
    }
</script>
<style lang="less" scoped>
    .page_root {
        width: 100%;
        height: 100%;
        overflow: auto;
    }
    .page_root :deep(.@{ant-prefix}-spin-nested-loading),
    .page_root :deep(.@{ant-prefix}-spin-container) {
        height: 100%;
    }
    .page_root :deep(.@{ant-prefix}-spin-container .@{ant-prefix}-table-wrapper) {
        display: flex;
        flex-flow: column nowrap;
        justify-content: flex-start;
    }
    .page_root :deep(.@{ant-prefix}-table) {
        flex: auto;
        overflow: auto;
    }
    .table-moreBtn_down {
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
        width: 100px;
    }

    .table-moreBtn_menu :deep(.table-moreBtn_menu-item):hover {
        background: #ebf1ff;
    }

    /*  表格树结构样式处理，展开按钮层级增加*/
    :deep(.@{ant-prefix}-table-row-expand-icon) {
        z-index: 1;
    }
    /*  表格树结构 由于每个表格项采用自定义组件，使用绝对定位布局，开启树结构导致显示异常，暂时使用层级定位位置 */
    :deep(.@{ant-prefix}-table-row-level-1 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
        left: 15px !important;
        width: calc(100% - 15px);
    }
    :deep(.@{ant-prefix}-table-row-level-2 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
        left: 30px !important;
        width: calc(100% - 30px);
    }
    :deep(.@{ant-prefix}-table-row-level-3 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
        left: 45px !important;
        width: calc(100% - 45px);
    }
    :deep(.@{ant-prefix}-table-row-level-4 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
        left: 60px !important;
        width: calc(100% - 60px);
    }

    /* 穿梭框改变默认样式，为根据组件样式控制左右栏宽度。 */
    :deep(.@{ant-prefix}-transfer-list) {
        height: 100%;
        width: 50%;
    }
    .body {
        height: 100%;
    }
    .top-search {
        padding: 16px 24px;
        padding-bottom: 0;
        background-color: #fff;
        margin-bottom: 16px;
    }
    .content {
        padding: 12px 24px;
        height: 100%;
        background-color: #fff;
    }
    .table-top {
        display: flex;
        justify-content: space-between;
        margin-bottom: 16px;
        align-items: center;
    }
    .tip-msg {
        padding-left: 8px;
        border-left: 4px solid #3875ff;
        height: 16px;
        font-size: 16px;
        font-weight: 600;
        line-height: 16px;
    }
    .right-btn {
        display: flex;
        gap: 8px;
    }
    .form-div :deep(.ant3-form-item-label) {
        width: 80px;
    }
    .table-box :deep(.@{ant-prefix}-table-tbody) tr > td {
        font-size: 14px;
        font-weight: 400;
        color: #262626;
        border-bottom: 1px solid #d9d9d9;
        padding: 8px 16px;
        word-break: break-all;
    }
</style>
